package com.android.nfctouch.ui.activity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Parcelable;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.baselibrary.interface_.OkHttpCallBack;
import com.android.baselibrary.responce.BaseResponce;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.util.AnimUtil;
import com.android.baselibrary.view.Comm_HeadView;
import com.android.baselibrary.view.MultiStateView;
import com.android.nfctouch.R;
import com.android.nfctouch.constants.Constants;
import com.android.nfctouch.manager.API_Manager;
import com.android.nfctouch.manager.SysConfigHelper;
import com.android.nfctouch.manager.UserManager;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

public class NFCActivity extends BaseActivity {

    @BindView(R.id.ll_content)
    LinearLayout ll_content;
    @BindView(R.id.view_bg)
    View view_bg;
    @BindView(R.id.iv_img)
    ImageView iv_img;


    NfcAdapter mNfcAdapter;
    PendingIntent mPendingIntent;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_nfc;
    }

    @Override
    protected void initView() {
        AnimUtil.enterFromBottom(ll_content);
        AnimUtil.fadeIn(view_bg);

        AnimationDrawable anim = (AnimationDrawable) iv_img.getDrawable();
        anim.start();
    }

    @Override
    protected void initData() {
        NfcInit(mContext);   //初始化
    }

    /**
     * 初始化nfc设置
     */
    public void NfcInit(Context activity) {
        mNfcAdapter = NfcCheck(mContext);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE);
        } else {
            mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        }
    }

    /**
     * 检查NFC是否打开
     */
    public static NfcAdapter NfcCheck(Context activity) {
        NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(activity);
        if (mNfcAdapter == null) {
            return null;
        } else {
            if (!mNfcAdapter.isEnabled()) {
                Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);
                activity.startActivity(setNfc);
            }
        }
        return mNfcAdapter;
    }

    /**
     * 获得焦点，按钮可以点击
     */
    @Override
    public void onResume() {
        super.onResume();
        //开启前台调度系统
        mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
    }

    /**
     * 暂停Activity，界面获取焦点，按钮可以点击
     */
    @Override
    public void onPause() {
        super.onPause();
        //恢复默认状态
        if (mNfcAdapter != null)
            mNfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.i("intent.getAction():" + intent.getAction());

        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())
                || NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            // 处理该intent
//            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
//            // 获取标签id数组
//            byte[] bytesId = tag.getId();
//            Log.i("bytesId:" + bytesId);

            String url = SysConfigHelper.getConfig(SysConfigHelper.Config_H5) + UserManager.getUserInfo(mContext).userId;
            Log.i("url:"+ url);
            writeNFCToTag(url, intent);

        }
    }

    /**
     * 读取NFC的数据
     */
    public String readNFCFromTag(Intent intent) {
        try {
            Parcelable[] rawArray = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            if (rawArray != null) {
                NdefMessage mNdefMsg = (NdefMessage) rawArray[0];
                NdefRecord mNdefRecord = mNdefMsg.getRecords()[0];
                if (mNdefRecord != null) {
                    String readResult = new String(mNdefRecord.getPayload(), "UTF-8");
                    return readResult;
                }
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 往nfc写入数据
     */
    public void writeNFCToTag(String data, Intent intent) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Ndef ndef = Ndef.get(tag);
        NdefFormatable ndefFormatable = NdefFormatable.get(tag);
        //创建写入数据
        NdefMessage newMessage = new NdefMessage(new NdefRecord[]{NdefRecord.createUri(data)});
//        NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{NdefRecord.createApplicationRecord(data)});
        try {
            if (ndef != null) {   //如果是NDEF类型的卡
                ndef.connect();
                ndef.writeNdefMessage(newMessage);
                ndef.close();
            } else if (ndefFormatable != null) {   //如果是 ndefFormatable 的卡
                //Ndef格式类
                //连接
                ndefFormatable.connect();
                //格式化并将信息写入标签
                ndefFormatable.format(newMessage);
            }
            CommToast.showToast(mContext, "写入成功");
            Log.i("写入成功");
            finish();
        } catch (Exception e) {
            e.printStackTrace();
            CommToast.showToast(mContext, "写入失败，卡片不支持");
        }
    }

    @OnClick({R.id.iv_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                finish();
                break;
        }
    }
}
